package com.liuceng.mps.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * Utils - Web
 * 
 */
public final class WebUtils {

  public static String getIpAddr(final HttpServletRequest request) {
    String ip = request.getHeader("X-Forwarded-For");
    if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("Proxy-Client-IP");
    }
    if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("X-Real-IP");
    }
    if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getRemoteAddr();
    }
    // 应对x-forwarded-for 中返回多个服务器ip的情况
    if (StringUtils.isNotBlank(ip) && (ip.split(",").length > 1)) {
      String realIp = ip.split(",")[0];
      // logger.error("this ip:" + realIp + " is cut from origin ips:" +
      // ip);
      ip = realIp;
    }
    return ip;
  }

}
